package com.quanta.edaily.controller;

import com.alibaba.fastjson.JSON;
import com.quanta.edaily.bean.JsonResponse;
import com.quanta.edaily.utils.youdao.AuthV3Util;
import com.quanta.edaily.utils.youdao.HttpUtil;
import jakarta.annotation.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 网易有道智云翻译服务api调用demo
 * api接口: https://openapi.youdao.com/api
 */
@RestController
@RequestMapping("/trans")
public class TranslateController {

    @Value("${APP_KEY}")
    private String APP_KEY;     // 您的应用ID
    @Value("${APP_SECRET}")
    private String APP_SECRET;  // 您的应用密钥

    @PostMapping ()
    public JsonResponse trans(@RequestParam String q,
                              @RequestParam @Nullable String from,
                              @RequestParam @Nullable String to
                              ) throws NoSuchAlgorithmException {
        // 添加请求参数
        if(from==null||from.isEmpty()) from="auto";
        Map<String, String[]> params = createRequestParams(q, from, to);
        // 添加鉴权相关参数
        AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        // 请求api服务
        byte[] result = HttpUtil.doPost("https://openapi.youdao.com/api", null, params, "application/json");
        // 打印返回结果
        if (result != null) {
//            String s = new String(result, StandardCharsets.UTF_8);
            return JsonResponse.success("翻译成功", JSON.parse(result));
        }
        System.exit(1);
        return JsonResponse.systemError("翻译失败");
    }

    private static Map<String, String[]> createRequestParams(String q, String from, String to) {
        /*
         * note: 将下列变量替换为需要请求的参数
         * 取值参考文档: https://ai.youdao.com/DOCSIRMA/html/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E7%BF%BB%E8%AF%91/API%E6%96%87%E6%A1%A3/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1-API%E6%96%87%E6%A1%A3.html
         */
//        String vocabId = "您的用户词表ID";

        return new HashMap<String, String[]>() {{
            put("q", new String[]{q});
            put("from", new String[]{from});
            put("to", new String[]{to});
            put("ext", new String[]{"mp3"});
//            put("strict", new String[]{Boolean.toString(strict)});
//            put("vocabId", new String[]{vocabId});
        }};
    }
}
